import os
import time

import pandas
from cpgzh import *
from setup import *
from pgzero.loaders import root
import json


class StudentCard:
    "学生卡牌"

    def __init__(self, data):
        x, y = pos = (480 * SCALE, 400 * SCALE)
        self.pics = {"待机": [], "攻击": [], "受伤": [], "死亡": []}
        self.actor = Actor(data["pic"], center=pos)
        self.actor.animate_fps = 10
        for i in self.actor.images:
            if "待机" in i:
                self.pics["待机"].append(i)
            elif "攻击" in i:
                self.pics["攻击"].append(i)
            elif "受伤" in i:
                self.pics["受伤"].append(i)
            elif "死亡" in i:
                self.pics["死亡"].append(i)
        self.images = self.pics["待机"]
        self.data = data
        self.status = "待机"
        self.id = data["id"]
        self.effect = []
        self.nowScore = 0
        self.pen = Pen()
        fonts = [Font() for i in range(3)]
        for i in fonts:
            i.fontname = "simyou"
            i.bold = True
        fonts[0].color = "red"
        fonts[0].fontsize = 20
        fonts[1].color = "#aa1199"
        fonts[1].fontsize = 16
        fonts[2].color = "#00aa33"
        fonts[2].fontsize = 16
        self._x = x
        self._y = y
        self.fonts = fonts
        self.bg = Actor("伙伴详情弹窗背景-动画_1-000", center=pos)
        self.bg.scale = (0.4 * SCALE, 0.5 * SCALE)
        if self.actor.width < self.actor.height:
            self.actor.scale = 165 * SCALE / self.actor.height
        else:
            self.actor.scale = 165 * SCALE / self.actor.width

    @property
    def status(self):
        "状态"
        return self.status

    @status.setter
    def status(self, status):
        "设置造型"
        self.actor.images = self.pics[status]

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        self._x = x
        self.actor.x = self._x
        self.bg.x = self._x

    @property
    def y(self):
        return self._y

    @y.setter
    def y(self, y):
        self._y = y
        self.actor.y = self._y
        self.bg.y = self._y

    def draw(self):
        "绘制角色"
        self.bg.draw()
        self.actor.draw()
        x, y = self.bg.pos
        pen = self.pen
        fonts = self.fonts
        pen.text(
            self.data["name"], center=(x - 50 * SCALE, y - 135 * SCALE), font=fonts[0]
        )
        pen.text(
            f"总分：{self.data['score']}",
            center=(x - 50 * SCALE, y - 115 * SCALE),
            font=fonts[1],
        )
        pen.text(
            f"本节课得分：{self.nowScore}",
            center=(x - 50 * SCALE, y - 95 * SCALE),
            font=fonts[2],
        )

    def update(self):
        "更新数据"
        for e in self.effect:
            e.y += e.speed
            e.speed -= 0.1
            if e.bottom < 0:
                e.hp = 0
            if e.image == e.images[-1]:
                e.animate_fps = 0
        self.effect = [e for e in self.effect if e.hp > 0]
        if self.actor.image in [
            self.pics["攻击"][-1],
            self.pics["受伤"][-1],
        ]:
            self.status = "待机"
        if self.actor.image == self.pics["死亡"][-1]:
            self.actor.animate_fps = 0

    def atk(self, atk):
        "攻击"
        self.data["score"] += atk
        self.nowScore += atk
        if atk > 0:
            self.actor.images = self.pics["攻击"]
            sounds.cheer.play()
            name = "胜利特效-sys"
        else:
            self.actor.images = self.pics["受伤"]
            sounds.ya.play()
            name = "失败特效-sys"
        e = Actor(name, center=(480 * SCALE, 0))
        e.animate_fps = 0
        e.speed = 10
        e.scale = 0.7 * SCALE
        e.hp = 1
        master.create_delay_tasks(e.next_image, seconds=0.1, times=len(e.images) - 1)
        self.effect.append(e)

    def animate_to(self, x, y):
        "运动"
        animate(self.actor, duration=1, midbottom=(x, y))
        animate(self.bg, duration=1, midbottom=(x, y))
        self.x, self.y = x, y

    def collide_pixel(self, actor):
        "碰撞"
        return self.actor.collide_pixel(actor)


class Students:
    def __init__(self, classid, lastPage, nextPage) -> None:
        "学生主界面"
        self.font = Font()
        self.font.fontname = "simyou"
        bg1 = Actor(f"主场景背景")
        bg2 = Actor(f"主场景背景")
        bg1.scale = SCALE
        bg2.scale = SCALE
        bg1.left = 0
        bg2.left = bg1.right
        bg1.top = bg2.top = 0
        with open(os.path.join(root, "datas.json"), "r", encoding="utf-8") as f:
            datas = json.load(f)
        cnt = 0
        students = []
        for i in datas["students"]:
            if classid in i["classid"]:
                a = StudentCard(i)
                x, y = (
                    100 * SCALE + cnt % 4 * 180 * SCALE,
                    270 * SCALE + cnt % 8 // 4 * 250 * SCALE,
                )
                a.animate_to(x, y)
                a.id = i["id"]
                a.name = i["name"]
                a.data = i
                students.append(a)
                cnt += 1
        self.startTime = time.time()
        lastPage.pos = 850 * SCALE, 500 * SCALE
        nextPage.pos = 900 * SCALE, 500 * SCALE
        armBG = Actor("队伍选择弹窗背景-动画_1-000")
        armBG.scale = 1.5 * SCALE
        armBG.topleft = (800 * SCALE, 0)
        releaseArms = Actor("弹窗关闭按钮-normal-000", center=(870 * SCALE, 400 * SCALE))
        releaseArms.scale = 0.7 * SCALE
        self.arms = []
        armsName = [
            "物品购买交互图标/物品购买交互图标-锤子-000",
            "商店价格类型图标/商店价格类型图标-动画_1-000",
            "商店价格类型图标/商店价格类型图标-动画_1-001",
            "物品购买交互图标/物品购买交互图标-特级宝玉-000",
        ]
        atks = [-1, 1, 3, 5]
        y = 50 * SCALE
        for i in range(len(atks)):
            a = Actor(armsName[i], center=(870 * SCALE, y))
            a.x0, a.y0 = a.x, a.y
            a.atk = atks[i]
            if a.height > 80 * SCALE:
                a.scale = 80 * SCALE / a.height
            y += 90 * SCALE
            self.arms.append(a)
        self.page = 0
        self.students = students
        self.actors = [bg1, bg2, armBG, lastPage, nextPage, releaseArms] + students
        self.bgs = [bg1, bg2]
        self.arm = 0
        self.datas = datas

    def update(self):
        "更新数据"
        students = self.students[self.page * 8 : self.page * 8 + 8]
        for s in self.students:
            if s in students:
                s.update()
                s.show = 1
            else:
                s.show = 0
        for bg in self.bgs:
            bg.x -= 1
            if bg.right <= 0:
                bg.left = 960 * SCALE

    def draw(self):
        "绘制角色"
        actors = self.actors[:6] + [s for s in self.students if s.show]
        for a in actors:
            a.draw()
        for a in self.arms:
            a.draw()
        for s in self.students:
            for e in s.effect:
                e.draw()

    def atkEffect(self):
        "攻击效果"

        def tLeft():
            "左转"
            self.arm.angle += 10

        def home():
            "归位"
            self.arm.angle = 0

        master.create_delay_tasks(tLeft, 0.05, 10)
        master.create_delay_tasks(home, 0.6)
        
